package com.jueling.culture.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linp
 * @date 2022/02/18
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "USER_INFO")
public class UserInfo {

    public static transient ThreadLocal<UserInfo> currentUser=new ThreadLocal<>();

    private final static transient String MD5SALT="md5salt";

    /**
     * 用户id自增主键
     */
    @Id
    @Column(name = "user_id")
    private String userId;

    /**
     * 用户名
     */
    @Column(name = "user_name")
    private String userName;

    /**
     * 姓名
     */
    private String name;

    /**
     * 密码
     */
    private String password;

    /**
     * 手机号
     */
    private String phone;

    /**
     * 创建时间
     */
    @Column(name = "create_time")
    private Date createTime;

    /**
     * 更新时间
     */
    @Column(name = "update_time")
    private Date updateTime;

    /**
     * 状态：0-停用、1-启用 
     */
    private Integer state;

    /**
     * 角色id
     */
    @Column(name = "role_id")
    private Integer roleId;

    /**
     * 管辖范围
     */
    @Column(name = "UNDER_CUST_ID")
    private String underCustId;

    @Transient
    private String underCustName;

    @Transient
    private String random;

    @Transient
    private String roleName;


    /**
     * 用户权限
     */
    @Transient
    private List<UserAuthority> userAuthority;

    /**
     * 密码加密
     * @param userName
     * @param password
     * @return
     */
    public static String getMD5Password(String userName,String password){
        return DigestUtils.md5Hex(password+userName+MD5SALT);
    }

    /**
     * 将user对象转为map
     * @param userInfo
     * @return
     */
    public static Map<String,Object> copyToMap(UserInfo userInfo){
        Map<String,Object> map = new HashMap<>();
        map.put("userInfo", JSON.toJSONString(userInfo));
        return map;
    }

    /**
     * 将map转为user对象
     * @param map
     * @return
     */
    public static UserInfo turnMapToUser(Map<String, Object> map){
        return JSONObject.parseObject((String)map.get("userInfo"), UserInfo.class);
    }

}